<script setup lang="ts">

import {listLatestPosts, listPostsByCat, Post} from "@/net/controller/post-controller.ts";
import {onMounted, ref, watch} from "vue";
import PostComponent from "../component/PostComponent.vue";
import router from "@/router";

const currentCatId = () => {
  return location.pathname.split("/")[location.pathname.split("/").length - 1]
}

const catId = ref(currentCatId())

watch(router.currentRoute, () => {
  catId.value = currentCatId()
  updatePosts(postsCurrentPage.value)
})

const posts = ref<Post[]>([])
const postsTotal = ref(1)
const postsCurrentPage = ref(1)


function updatePosts(page: number) {
  listPostsByCat(page, Number.parseInt(catId.value)).then((res) => {
    posts.value = res.records
    postsTotal.value = res.total
  })
}

onMounted(() => {
  updatePosts(1)
})

</script>

<template>
  <main>
    <PostComponent v-for="(post, index) in posts" :post="post" :key="index" />

    <el-pagination layout="prev, pager, next"
                   style="margin-top: 1rem"
                   size="default"
                   :page-size="20"
                   :total="postsTotal"
                   v-model:current-page="postsCurrentPage"
                   @current-change="updatePosts"
    />
  </main>
</template>

<style scoped>

</style>